# -*- coding: utf-8 -*-
"""
@Time    : 2024/7/17 11:19 
@Author  : ZhangShenao 
@File    : 5.PlanAndExecute计划与执行代理.py 
@Desc    : 使用Plan and execute 计划与执行代理模式

Plan and execute代理模式
通过首先计划要做什么,然后执行子任务来实现目标

"""
import os

import dotenv
from langchain.chains.llm_math.base import LLMMathChain
from langchain_community.utilities import SerpAPIWrapper
from langchain_core.tools import Tool
from langchain_experimental.plan_and_execute import load_chat_planner, load_agent_executor, PlanAndExecute
from langchain_openai import ChatOpenAI

# 加载环境变量
dotenv.load_dotenv()

# 创建LLM
llm = ChatOpenAI(model_name='gpt-3.5-turbo', openai_api_base=os.getenv('OPENAI_API_BASE'))

# 创建SerpAPIWrapper工具
serp_api = SerpAPIWrapper()

# 创建LLMMathChain
llm_math_chain = LLMMathChain.from_llm(llm=llm, verbose=True)

# 创建工具箱
tools = [
    Tool(
        name='Search',
        func=serp_api.run,
        description='useful for when you need to answer questions about current events'
    ),
    Tool(
        name='Calculator',
        func=llm_math_chain.run,
        description='useful for when you need to answer questions about math'
    ),
]

# 创建Planner,用于生成计划
planner = load_chat_planner(llm)

# 创建Executor,用于执行计划
executor = load_agent_executor(llm, tools, verbose=True)

# 创建Plan And Execute模式的代理
agent = PlanAndExecute(planner=planner, executor=executor, verbose=True)

# 执行代理
agent.run('在纽约，100美元能买几束玫瑰？')
